//
//  ViewController.m
//  Homework_10
//
//  Created by 徐昊 on 16/7/27.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "ViewController.h"
#import "UIView+Frame.h"
#import "FormalTableViewCell.h"
#import "ImageTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "Model.h"

#define kTableViewCellName @"reuse"
#define kTableViewImageCellName @"reuseImage"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrOfModel;
@property (nonatomic, strong) NSDictionary *sourceDictionary;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) NSMutableArray *cycleImageArray;
@property (nonatomic, strong) UIPageControl *page;
@property (nonatomic, strong) UIScrollView *cycleImage;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *loan_button;
@property (nonatomic, strong) UIButton *market_button;
@property (nonatomic, strong) UIButton *basePrice_button;
@property (nonatomic, strong) UIButton *secondHand_button;
@property (nonatomic, strong) UILabel *loan_label;
@property (nonatomic, strong) UILabel *market_label;
@property (nonatomic, strong) UILabel *basePrice_label;
@property (nonatomic, strong) UILabel *secondHand_label;
@property (nonatomic, strong) Model *modelOfInfo;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationController.navigationBarHidden = YES;
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[FormalTableViewCell class] forCellReuseIdentifier:kTableViewCellName];
    [_tableView registerClass:[ImageTableViewCell class] forCellReuseIdentifier:kTableViewImageCellName];
    [self handleHeaderView];
    [self setButton];
    [self handleInfo];
}
- (void)handleInfo {
    NSString *path = [[NSBundle mainBundle]pathForResource:@"YiChe" ofType:@"plist"];
    NSDictionary *dictionOfSource = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *arraySource = [[dictionOfSource objectForKey:@"data"] objectForKey:@"list"];
    self.arrOfModel = [NSMutableArray array];
    for (NSDictionary *diction in arraySource) {
        Model *model = [[Model alloc] init];
        model.title = [diction objectForKey:@"title"];
        model.picCover = [diction objectForKey:@"picCover"];
        [_arrOfModel addObject:model];
    }
}
#pragma mark - 数据处理
- (void)handleData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"YiChe" ofType:@"plist"];
    self.sourceDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
}
#pragma mark - 轮播图部分
- (void)handleHeaderView {
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.h_width, self.view.h_height / 2 - 50)];
        // 如果tableHeaderView要进行频繁修改, 必须加上
        // beginUpdates
        // endUpdated
    [_tableView beginUpdates];
    _tableView.tableHeaderView = _headerView;
    [_tableView endUpdates];
    _cycleImage = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.h_width, 200)];
    _cycleImage.showsHorizontalScrollIndicator = NO;
    _cycleImage.backgroundColor = [UIColor redColor];
    [_headerView addSubview:_cycleImage];
    _cycleImage.contentSize = CGSizeMake(self.view.h_width * 6, 200);
    _cycleImage.pagingEnabled = YES;
    _cycleImage.bounces = NO;
    _cycleImage.delegate = self;
    NSDictionary *data = [_sourceDictionary objectForKey:@"data"];
    NSDictionary *cycleArray = [data objectForKey:@"cycleImage"];
    NSLog(@"%@", cycleArray);
    _cycleImageArray = [NSMutableArray array];
    for (NSDictionary *dictionary in cycleArray) {
        NSString *picCover = [dictionary objectForKey:@"picCover"];
        [_cycleImageArray addObject:picCover];
    }
    NSObject *obj = [_cycleImageArray lastObject];
    NSObject *obj2 = [_cycleImageArray firstObject];
    [_cycleImageArray addObject:obj2];
    [_cycleImageArray insertObject:obj atIndex:0];
    for (int i = 0; i < _cycleImageArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.h_width * i, 0, self.view.h_width, 200)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:_cycleImageArray[i]] placeholderImage:[UIImage imageNamed:@"@1"]];
            NSLog(@"%@", _cycleImageArray[i]);
        [_cycleImage addSubview:imageView];
    }
    _cycleImage.contentOffset = CGPointMake(self.view.h_width, 0);
    [self addPage];
}
- (void)addPage{
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(self.view.h_width / 2 - 50, 200 - 40, 100, 40)];
    self.page.currentPage = 0;
    self.page.numberOfPages = 4;
    [self.headerView addSubview:self.page];
    [self.page addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
    [self addTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _cycleImage) {
        NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width;
        self.page.currentPage = index - 1;
        if (index == 5) {
            self.page.currentPage = 0;
            scrollView.contentOffset = CGPointMake(self.view.h_width * 1, 0);
        }
        if (index == 0) {
            self.page.currentPage = 4;
            scrollView.contentOffset = CGPointMake(self.view.h_width * 4, 0);
        }
    }
}
- (void)click:(UIPageControl *)page {
    self.cycleImage.contentOffset = CGPointMake(self.view.h_width * (page.currentPage + 1), 0);
}
- (void)addTimer {
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)nextImage {
    NSInteger page = self.page.currentPage;
    if (page == 3) {
        page = 0;
    } else {
        page++;
    }
    self.cycleImage.contentOffset = CGPointMake((page + 1) * self.view.h_width, 0);
    self.page.currentPage = page;
    for (UIScrollView *scroll in self.cycleImage.subviews) {
        if ([scroll isKindOfClass:[UIScrollView class]]) {
            scroll.zoomScale = 1;
        }
    }
}
- (void)closeTimer {
    [self.timer invalidate];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self closeTimer];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [self addTimer];
}
- (void)setButton {
    self.loan_button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.market_button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.basePrice_button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.secondHand_button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat buttonY = 220;
    CGFloat buttonWidth = 50;
    CGFloat buttonHegiht = 50;
    CGFloat leftMargin = 20;
    CGFloat rightMargin = 20;
    CGFloat buttonSpaceing = (self.view.h_width - 4 * buttonWidth - leftMargin - rightMargin) / 3;
    _loan_button.frame = CGRectMake(leftMargin, buttonY, buttonWidth, buttonHegiht);
    _market_button.frame = CGRectMake(leftMargin + buttonWidth + buttonSpaceing, buttonY, buttonWidth, buttonHegiht);
    _basePrice_button.frame = CGRectMake(leftMargin + buttonWidth * 2 + buttonSpaceing * 2, buttonY, buttonWidth, buttonHegiht);
    _secondHand_button.frame = CGRectMake(leftMargin + buttonWidth * 3 + buttonSpaceing * 3, buttonY, buttonWidth, buttonHegiht);
    [_loan_button setImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
    [_market_button setImage:[UIImage imageNamed:@"2"] forState:UIControlStateNormal];
    [_basePrice_button setImage:[UIImage imageNamed:@"3"] forState:UIControlStateNormal];
    [_secondHand_button setImage:[UIImage imageNamed:@"4"] forState:UIControlStateNormal];
    // 创建四个label
    CGFloat labelY = 280;
    CGFloat labelWidth = 80;
    CGFloat labelHeight = 10;
    CGFloat labelSpacing = buttonSpaceing - 30;
    
    self.loan_label = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, labelY, labelWidth, labelHeight)];
    self.market_label = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin + labelWidth + labelSpacing, labelY, labelWidth, labelHeight)];
    self.basePrice_label = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin + labelWidth * 2 + labelSpacing * 2, labelY, labelWidth, labelHeight)];
    self.secondHand_label = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin + labelWidth * 3 + labelSpacing * 3, labelY, labelWidth, labelHeight)];
    _loan_label.text = @"贷款买车";
    _market_label.text = @"直销车型";
    _basePrice_label.text = @"底价买车";
    _secondHand_label.text = @"二手车";
    [_headerView addSubview:_loan_button];
    [_headerView addSubview:_market_button];
    [_headerView addSubview:_basePrice_button];
    [_headerView addSubview:_secondHand_button];
    [_headerView addSubview:_loan_label];
    [_headerView addSubview:_market_label];
    [_headerView addSubview:_basePrice_label];
    [_headerView addSubview:_secondHand_label];
}
// 分区头视图设置
//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
//    return self.view.h_height / 2 - 50;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.h_width, self.view.h_height / 2)];
//    view.backgroundColor = [UIColor redColor];
//    return view;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arrOfModel.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.row % 5 == 0 && indexPath.row != 0) {
//        ImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewImageCellName];
//        return cell;
//    } else {
    FormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellName];
    cell.carIntroduce.text = [_arrOfModel[indexPath.row] title];
    [cell.carImageView sd_setImageWithURL:[NSURL URLWithString:[_arrOfModel[indexPath.row] picCover]] placeholderImage:[UIImage imageNamed:@"@1"]];
    
    return cell;
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
